package com.android.aishangauction.activity.mine;

import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.aishangauction.R;
import com.android.aishangauction.model.data;
import com.android.aishangauction.model.dataCallback;
import com.android.aishangauction.model.member.RefoundDetailData;
import com.android.aishangauction.model.member.RefoundDetailDataCallback;
import com.android.aishangauction.model.member.RefoundMsgData;
import com.android.aishangauction.model.member.RefoundMsgData2;
import com.android.aishangauction.model.member.RefoundMsgData2Callback;
import com.android.aishangauction.model.member.RefoundMsgDataCallback;
import com.android.aishangauction.utils.ConstantsUrl;
import com.android.aishangauction.utils.HttpUtils;
import com.android.aishangauction.utils.MyLog;
import com.android.aishangauction.utils.ObjectUtils;
import com.android.aishangauction.utils.update.StorageUtils;
import com.android.aishangauction.view.MyGridView;
import com.android.aishangauction.view.dialog.MainMsg;
import com.bumptech.glide.Glide;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class RefundDetailActivity extends TakePhotoActivity {


    @BindView(R.id.main_top_title)
    TextView mainTopTitle;
    @BindView(R.id.ll_detail_stauts_img)
    ImageView llDetailStautsImg;
    @BindView(R.id.ll_detail_stauts_tv)
    TextView llDetailStautsTv;
    @BindView(R.id.ll_detail_stauts_reason)
    TextView llDetailStautsReason;
    @BindView(R.id.ll_detail_back)
    TextView llDetailBack;
    @BindView(R.id.ll_detail_contact)
    TextView llDetailContact;
    @BindView(R.id.ll_detail)
    LinearLayout llDetail;
    @BindView(R.id.ll_express_store_name)
    TextView llExpressStoreName;
    @BindView(R.id.ll_express_store_phone)
    TextView llExpressStorePhone;
    @BindView(R.id.ll_express_store_address)
    TextView llExpressStoreAddress;
    @BindView(R.id.ll_express_edit_name)
    EditText llExpressEditName;
    @BindView(R.id.ll_express_edit_number)
    EditText llExpressEditNumber;
    @BindView(R.id.ll_express_edit_ll)
    LinearLayout llExpressEditLl;
    @BindView(R.id.ll_express_tv_name)
    TextView llExpressTvName;
    @BindView(R.id.ll_express_tv_number)
    TextView llExpressTvNumber;
    @BindView(R.id.ll_express_tv_ll)
    LinearLayout llExpressTvLl;
    @BindView(R.id.post)
    Button post;
    @BindView(R.id.ll_express)
    ScrollView llExpress;
    @BindView(R.id.service_apply)
    TextView serviceApply;
    @BindView(R.id.result_apply)
    TextView resultApply;
    @BindView(R.id.content_apply)
    EditText contentApply;
    @BindView(R.id.gridphoto)
    MyGridView gridphoto;
    @BindView(R.id.photo)
    Button photo;
    @BindView(R.id.ll_apply)
    ScrollView llApply;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;
    private String refund_id;
    private boolean networkConnected;
    private RefundDetailActivity mcontext;
    private int refund_type;
    private TakePhoto takePhoto;
    private ArrayList<TImage> mList = new ArrayList<>();
    private MainMsg mdialog;
    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_refund_detail);
        ButterKnife.bind(this);
        mcontext = RefundDetailActivity.this;

        refund_type = getIntent().getIntExtra("refund_type", 0);
        refund_id = getIntent().getStringExtra("refund_id");
        switch (refund_type) {
            case 0:
                initTitle("退款详情");
                llDetail.setVisibility(View.VISIBLE);
                GetDetail(refund_id);
                break;
            case 1:
                initTitle("退货信息");
                llExpress.setVisibility(View.VISIBLE);
                int refund_number = getIntent().getIntExtra("refund_number", 1);
                if (refund_number == 1) {
                    llExpressEditLl.setVisibility(View.VISIBLE);
                    GetExpressAddress(refund_id);

                } else {
                    post.setText("返回");
                    llExpressTvLl.setVisibility(View.VISIBLE);
                    GetExpressMessage(refund_id);

                }
                break;
            case 2:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                initTitle("提交申请");
                llApply.setVisibility(View.VISIBLE);
                initUIApply();
                break;
        }

    }


    private void initTitle(String tv) {


        ObjectUtils.StatusBarWhiteBg(mcontext,false);

        mainTopTitle.setText(tv);


    }

    /**
     * 申请详情
     */
    private void GetDetail(String id) {
        networkConnected = ObjectUtils.isNetworkConnected(this);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORREFOUNDDETAIL + "?refund_id=" + id;

        MyLog.e("地址", "" + address);
        if (networkConnected) {
            HttpUtils.get(address, null, new RefoundDetailDataCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                        }

                        @Override
                        public void onResponse(RefoundDetailData response, int id) {

                            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);

                            if (response.getCode() == 0) {
                                llDetailStautsTv.setText(response.getData().getMsg() + "");
                                if (response.getData().getReason() == null) {

                                    llDetailStautsImg.setImageResource(R.mipmap.tui_yes);
                                } else {

                                    llDetailStautsImg.setImageResource(R.mipmap.tui_no);
                                    llDetailStautsReason.setVisibility(View.VISIBLE);
                                    llDetailStautsReason.setText("拒绝原因：" + response.getData().getReason());
                                    llDetailContact.setVisibility(View.VISIBLE);
                                }
                            } else {
                                noData.setVisibility(View.VISIBLE);
                                noDataTv.setText(response.getMsg());
                                noDataTv.setVisibility(View.VISIBLE);
                            }

                        }
                    }

            );
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(this, "网络未连接");
        }

    }


    /**
     * 退货信息
     */

    private void GetExpressAddress(String id) {
        networkConnected = ObjectUtils.isNetworkConnected(this);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORREFOUNDADDRESS + "?refund_id=" + id;
        MyLog.e("地址", "" + address);
        if (networkConnected) {
            HttpUtils.get(address, null, new RefoundMsgData2Callback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                        }

                        @Override
                        public void onResponse(RefoundMsgData2 response, int id) {
                            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                            if (response.getCode() == 0) {
                                if (response.getData() != null) {


                                    llExpressStoreName.setText(response.getData().getName());
                                    llExpressStorePhone.setText(response.getData().getMobile());
                                    llExpressStoreAddress.setText(response.getData().getAddress());

                                } else {

                                    llExpressStoreName.setText("商家还未填写");
                                    llExpressStorePhone.setText("商家还未填写");
                                    llExpressStoreAddress.setText("商家还未填写");

                                }


                            } else {
                                noData.setVisibility(View.VISIBLE);
                                noDataTv.setText(response.getMsg());
                                noDataTv.setVisibility(View.VISIBLE);
                            }
                        }
                    }

            );
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(this, "网络未连接");
        }

    }

    private void GetExpressMessage(String id) {
        networkConnected = ObjectUtils.isNetworkConnected(this);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORREFOUNDMESSAGE + "?refund_id=" + id;
        MyLog.e("地址", "" + address);
        if (networkConnected) {
            HttpUtils.get(address, null, new RefoundMsgDataCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                        }

                        @Override
                        public void onResponse(RefoundMsgData response, int id) {
                            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                            if (response.getCode() == 0) {
                                if (response.getData() != null) {
                                    llExpressStoreName.setText(response.getData().getName());
                                    llExpressStorePhone.setText(response.getData().getMobile());
                                    llExpressStoreAddress.setText(response.getData().getAddress());
                                    llExpressTvName.setText(response.getData().getExpress());
                                    llExpressTvNumber.setText(response.getData().getExpress_num());

                                }


                            } else {
                                noData.setVisibility(View.VISIBLE);
                                noDataTv.setText(response.getMsg());
                                noDataTv.setVisibility(View.VISIBLE);
                            }
                        }

                    }

            );
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(this, "网络未连接");
        }

    }

    //提交申请
    private void PostContent(String id, String express, String express_num) {
        networkConnected = ObjectUtils.isNetworkConnected(this);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORREFOUNDTUIDINGDANG;
        MyLog.e("地址", "" + address);
        if (networkConnected) {
            progressLoading.setVisibility(View.VISIBLE);
            HashMap<String, String> map = new HashMap<>();
            map.put("id", id);
            map.put("express", express);
            map.put("express_num", express_num);

            HttpUtils.post(address, map, new dataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    progressLoading.setVisibility(View.GONE);
                }

                @Override
                public void onResponse(data response, int id) {
                    progressLoading.setVisibility(View.GONE);

                    if (response.getCode() == 0) {
                        finish();

                    }
                    ObjectUtils.toast(mcontext, response.getMsg());
                }
            });
        } else {

            ObjectUtils.toast(this, "网络未连接");
        }
    }

    /**
     * 退款退货申请
     */
    private void initUIApply() {
        //初始化
        takePhoto = getTakePhoto();

        mdialog = new MainMsg(mcontext);
        mdialog.setOnSetCameraClickListener(new MainMsg.OnTaktPhotoClickListener() {
            @Override
            public void onClickCamera() {
                Uri uri = configCompress();
                takePhoto.onPickFromCapture(uri);
                mdialog.close();
            }

            @Override
            public void onClickGallery() {
                int size = mList.size();
                MyLog.e("总共size", "" + size);
                configCompress();
                takePhoto.onPickMultiple(5 - size);
                mdialog.close();
            }
        });
        adapter = new MyAdapter();
        gridphoto.setAdapter(adapter);
    }

    //压缩
    private Uri configCompress() {
        File dir = StorageUtils.getCacheDirectory(this);
        File file = new File(dir, getString(R.string.app_path) + System.currentTimeMillis() + ".png");
//        File file = new File(Environment.getExternalStorageDirectory(), getString(R.string.app_path) + System.currentTimeMillis() + ".png");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        Uri imageUri = Uri.fromFile(file);
        CompressConfig config = new CompressConfig.Builder().setMaxSize(100 * 1024).setMaxPixel(1000).create();
        takePhoto.onEnableCompress(config, true);
        return imageUri;
    }


    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        mList.addAll(result.getImages());
        adapter.notifyDataSetChanged();

    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mList.size() + 1;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {


            View view = getLayoutInflater().inflate(R.layout.ll_photo_item, parent, false);
            ImageView imageView = (ImageView) view.findViewById(R.id.ic_image_pick);
            Button delete = (Button) view.findViewById(R.id.button1);
            if (position == mList.size()) {

                Glide.with(mcontext).load(R.mipmap.icon_addpic_unfocused).into(imageView);
                delete.setVisibility(View.INVISIBLE);

                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        mdialog.show(mcontext.getWindow().getDecorView(), 1, null);
                    }
                });
                if (position == 5) {

                    imageView.setVisibility(View.GONE);
                }
            } else {
                if (mList.size() > 0) {
                    delete.setVisibility(View.VISIBLE);

                    Glide.with(mcontext).load(new File(mList.get(position).getCompressPath())).into(imageView);

                    delete.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            mList.remove(position);
                            notifyDataSetChanged();
                        }
                    });
                }


            }
            return view;
        }
    }

    //提交申请
    private void PostContent(String order_id, String type, String reason_id, String note) {
        networkConnected = ObjectUtils.isNetworkConnected(this);

        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORGET;
        MyLog.e("地址", "" + address);
        if (networkConnected) {
            progressLoading.setVisibility(View.VISIBLE);
            final HashMap<String, String> map = new HashMap<>();

            ArrayList<File> fileList = new ArrayList<>();


            for (int i = 0; i < mList.size(); i++) {
                File file = new File(mList.get(i).getCompressPath());
                fileList.add(file);
            }

            MyLog.e("上传图片", "imagePathList条数" + mList.size() + mList.toString());
            map.put("order_id", order_id);
            map.put("type", type);
            map.put("reason_id", reason_id);
            map.put("note", note);

            PostFormBuilder post = OkHttpUtils.post();

            if (fileList.size() > 0) {
                for (File file1 : fileList) {
                    post.addFile("pic[]", String.valueOf(System.currentTimeMillis()) + ".png", file1);
                }
            }


            post.url(address)
                    .params(map)
                    .build()
                    .execute(new dataCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            progressLoading.setVisibility(View.GONE);
                        }

                        @Override
                        public void onResponse(data response, int id) {
                            progressLoading.setVisibility(View.GONE);

                            ObjectUtils.toast(mcontext, response.getMsg());

                            if (response.getCode() == 0) {

                                finish();
                            }

                        }

                    });


        } else {

            ObjectUtils.toast(this, "网络未连接");
        }
    }

    @OnClick({R.id.main_top_back, R.id.ll_detail_back, R.id.post, R.id.photo, R.id.click_resetnetwork_refresh, R.id.ll_detail_contact, R.id.service_apply, R.id.result_apply})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_top_back:

                finish();
                break;
            case R.id.ll_detail_back:
                finish();
                break;
            case R.id.service_apply:
                final MainMsg mdialog = new MainMsg(mcontext);
                mdialog.show(mcontext.getWindow().getDecorView(), 2, null);
                mdialog.setPopListDataClickListener(new MainMsg.OnPopListDataClickListener() {
                    @Override
                    public void onData(String name, String id) {
                        serviceApply.setText(name);
                        id1 = id;
                        mdialog.close();
                    }
                });
                break;
            case R.id.result_apply:
                final MainMsg mdialog_result = new MainMsg(mcontext);
                mdialog_result.show(mcontext.getWindow().getDecorView(), 3, null);
                mdialog_result.setPopListDataClickListener(new MainMsg.OnPopListDataClickListener() {
                    @Override
                    public void onData(String name, String id) {
                        resultApply.setText(name);
                        id2 = id;
                        mdialog_result.close();
                    }
                });
                break;
            case R.id.post:
                if (post.getText().toString().trim().equals("返回")) {

                    finish();
                } else {

                    //提交
                    String name = llExpressEditName.getText().toString().trim();
                    String number = llExpressEditNumber.getText().toString().trim();
                    if (name.equals("") || number.equals("")) {

                        ObjectUtils.toast(this, "信息未填写完整");

                        return;
                    }
                    PostContent(refund_id, name, number);
                }
                break;
            case R.id.photo:
                String content = contentApply.getText().toString().trim();
                if (id1.equals("0") || id2.equals("0") || content.equals("")) {
                    ObjectUtils.toast(this, "信息填写完整");
                    return;

                }
                //提交申请
                PostContent(refund_id, id1, id2, content);

                break;
            case R.id.click_resetnetwork_refresh:
                switch (refund_type) {
                    case 0:
                        ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                        GetDetail(refund_id);
                        break;
                    case 1:
                        ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                        int refund_number = getIntent().getIntExtra("refund_number", 1);
                        if (refund_number == 1) {

                            GetExpressAddress(refund_id);

                        } else {

                            GetExpressMessage(refund_id);

                        }
                        break;
                    case 2:

                        break;
                }
                break;
            case R.id.ll_detail_contact:
                break;
        }
    }

    private String id1 = "1";
    private String id2 = "0";

}
